import random
import time


# 装饰器函数是一个代理，它要执行被装饰的函数，还要添加额外的功能
# 装饰器是一个函数，它可以装饰别的函数或类，所以它的参数通常是函数或者类，
# 它的返回值是一个带有装饰功能的函数
from threading import Thread
from threading import current_thread


class TimeRecorder:

    def __init__(self, target):
        self.target = target

    def __call__(self, *args, **kwargs):
        start = time.time()
        result = self.target(*args, **kwargs)
        end = time.time()
        print(f'{self.target.__name__}执行时间：{end - start:.3f}秒')
        return result


def record_time(func):

    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f'{func.__name__}执行时间：{end - start:.3f}秒')
        return result

    return wrapper


# download = record_time(download)
# @record_time
# download = TimeRecorder(download)
@TimeRecorder
def download(filename):
    print(current_thread().name)
    print(f'开始下载{filename}')
    time.sleep(random.randint(5, 10))
    print(f'{filename}下载完成')


@record_time
def upload(filename):
    print(current_thread().name)
    print(f'开始上传{filename}')
    time.sleep(random.randint(10, 15))
    print(f'{filename}上传完成')


@record_time
def main():
    print(current_thread().name)
    t1 = Thread(target=download, args=('Python从入门到住院.pdf', ), daemon=True)
    t1.start()
    t2 = Thread(name='foo', target=download, args=('MySQL从删库到跑路.avi', ), daemon=True)
    t2.start()
    t3 = Thread(target=upload, args=('北京有点热.avi', ), daemon=True)
    t3.start()
    t3.join()
    t1.join()
    t2.join()


if __name__ == '__main__':
    main()
